package com.tianfang.mytranmqconsumer.service;

import com.tianfang.mytranmqconsumer.common.params.MailParam;
import com.tianfang.mytranmqconsumer.listener.MqListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;


/**
 * 邮件发送业务逻辑类
 */
@Component
public class MailService {
    //读取application.properties文件中的属性，并赋值给mailFrom变量
    @Value("${spring.mail.username}")
    private String mailFrom;

    private static final Log log = LogFactory.getLog(MqListener.class);

	@Autowired
	private JavaMailSender mailSender;  //application.properties文件中配置的bean
    @Autowired
    private SimpleMailMessage simpleMailMessage; //BeanConfig类中定义bean

	/**
	 * 发送模板邮件
	 */
	public void mailSend(final MailParam mailParam) {
        log.info("==>开始发送邮件到邮件服务器");
        try {
            simpleMailMessage.setFrom(mailFrom);
            simpleMailMessage.setTo(mailParam.getTo()); // 接收人
            simpleMailMessage.setSubject(mailParam.getSubject());
            simpleMailMessage.setText(mailParam.getContent());
            mailSender.send(simpleMailMessage);
        } catch (MailException e) {
            throw e;
        }
        log.info("==>发送邮件到邮件服务器成功");
	}
}
